//
//  WeightChartView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/30.
//

import SwiftUI
import Charts

struct WDataItem : Identifiable{
    let id = UUID()
    let timeRange: String
    let weight: Double
}


struct WeightChartView: View {
    let data: [WDataItem]
    private let maxWeight: Double = 65
    
    var body: some View {
            Chart(data) { item in
                PointMark(
                    x: .value("时间", item.timeRange),
                    y: .value("体重", item.weight)
                )
                .symbolSize(0)
                .annotation(position: .overlay) {
                    Image("weight 1")
                        .frame(width: 12,height: 12)
                }
            }
            .chartXAxis {
                AxisMarks(values: .automatic) { value in
                    AxisGridLine(
                        stroke: StrokeStyle(
                            lineWidth: 0.5,
                            dash: [0, 0])
                    )
                    .foregroundStyle(value.index == 0 ? Color(hex: "#C1C1C1"):
                                        Color.clear)
                    if let time = value.as(String.self) {
                        AxisValueLabel {
                            let hour = getHourNumber(date: time)
                            if hour % 6 == 0{
                                Text(time)
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .frame(width: 100)
                            }
                        }
                    }
                }
            }
            .chartYScale(domain: 40...maxWeight)
            .chartYAxis {
                AxisMarks(position: .trailing,values: .stride(by: 5)) { value in
                    AxisGridLine(
                        stroke: StrokeStyle(
                            lineWidth: 0.5,
                            dash: [4, 2])
                    )
                    .foregroundStyle(Color(hex: "#C1C1C1"))
                    if let score = value.as(Double.self) {
                        AxisValueLabel {
                                Text("\(Int(score))")
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .padding(.leading,10)
                        }
                    }
                }
            }
            .frame(height: 200)
            .chartLegend(.hidden)
        }
    
    func getHourNumber(date:String) -> Int {
        if let colonIndex = date.firstIndex(of: ":") {
            let hourPart = date[..<colonIndex]
            print(String(hourPart))
            return Int(hourPart) ?? 0
        }
        return 0
    }
}

